﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;

using Noris.Tools.TraceVisualiser.Support;
using Noris.Tools.TraceVisualiser.Forms;
using Noris.Tools.TraceVisualiser.Components;

namespace Noris.Tools.TraceVisualiser.TraceData
{
    /// <summary>
    /// Vizuální třída, která zobrazuje data o projektu (TraceDocument).
    /// Vizuální vrstva je bindována na objekt this.Document { get; set; }.
    /// </summary>
	internal class DocumentPropertiesPanel : TabControl
	{
		#region Konstrukce
		public DocumentPropertiesPanel()
		{
			this._Init();
		}
		private void _Init()
		{
			this.SuspendLayout();

            this._FilterPresets = TraceDocument.GetPresetNames();

			this.Size = new System.Drawing.Size(480, 285);
            this.MinimumSize = new System.Drawing.Size(480, 285);
			this.Anchor = (AnchorStyles)(AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right);

            this._InitPageSimple();
			this._InitPageDoc();
			this._InitPageFilter();

            this.SizeChanged += new EventHandler(DocumentPropertiesPanel_SizeChanged);

			this.TabStop = false;

			this.PerformLayout();
			this.ResumeLayout(false);
		}

        void DocumentPropertiesPanel_SizeChanged(object sender, EventArgs e)
        {
            this._ResizePageSimple();
        }
        #endregion
        #region Eventy
        /// <summary>
        /// Event, který je vyvolán tlačítkem RUN na panelu
        /// </summary>
        public event EventHandler RunDocument;
        protected virtual void OnRunDocument()
        {
            if (this.RunDocument != null)
                this.RunDocument(this, EventArgs.Empty);
        }
        #endregion
        #region TabPage: Simple
        private void _InitPageSimple()
        {
            // Nová záložka:
            this.TabPageSimple = new TabPage();
            this.TabPages.Add(this.TabPageSimple);
            this.TabPageSimple.Bounds = this.ClientRectangle;
            this.TabPageSimple.Text = "Zadání projektu";

            // Do záložky přidat SimplePanel:
            this.SimplePanel = new SimpleProjectPanelMed();
            this.SimplePanel.Dock = DockStyle.Fill;
            this.SimplePanel.InitialDirectory = Steward.AppConfig.LastTracePath;
            this.SimplePanel.DialogFilter = TraceDocument.GetOpenTraceFilter("All files (*.*)|*.*");
            this.SimplePanel.FileSelectChanged += new SimpleProjectPanelAbs.FileSelectHandler(SimplePanel_FileSelectChanged);
            this.SimplePanel.Run += new EventHandler(SimplePanel_Run);

            this.TabPageSimple.Controls.Add(this.SimplePanel);
        }
        /// <summary>
        /// Událost vyvolaná poté, co uživatel něco vybere.
        /// Na základě toho naplním proměnné v okně.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void SimplePanel_FileSelectChanged(object sender, SimpleProjectPanelAbs.FileSelectChangeArgs args)
        {
            int fileCnt = args.Files.Count;
            string filePath = "";
            List<string> explicitFiles = null;
            string projectFile = "";
            string projectName = "";
            TraceFileRangeType fileRange = TraceFileRangeType.None;
            switch (args.FileSelect)
            {
                case SimpleProjectPanelAbs.FileSelectType.OneFile:
                    if (fileCnt == 1)
                    {
                        filePath = args.Files[0];
						if (this.DocumentIsNew)
                            TraceDocument.CreateProjectFileName(filePath, TraceDocument.CreateProjectNameMode.FullNameCopy, false, ref projectFile, ref projectName);
                        fileRange = TraceFileRangeType.OneFile;
                    }
                    break;
                case SimpleProjectPanelAbs.FileSelectType.OneDirectory:
                    if (fileCnt == 1)
                    {
                        filePath = args.Files[0];
						if (this.DocumentIsNew)
                            TraceDocument.CreateProjectFileName(filePath, TraceDocument.CreateProjectNameMode.DirectoryFromName, false, ref projectFile, ref projectName);
                        fileRange = TraceFileRangeType.OneDirectory;
                    }
                    break;
                case SimpleProjectPanelAbs.FileSelectType.SubDirectory:
                    if (fileCnt == 1)
                    {
                        filePath = args.Files[0];
						if (this.DocumentIsNew)
                            TraceDocument.CreateProjectFileName(filePath, TraceDocument.CreateProjectNameMode.Directory, false, ref projectFile, ref projectName);
                        fileRange = TraceFileRangeType.AllSubdirectories;
                    }
                    break;
                case SimpleProjectPanelAbs.FileSelectType.ExplicitFiles:
                    if (fileCnt >= 1)
                    {
                        explicitFiles = new List<string>(args.Files);
						if (this.DocumentIsNew)
                            TraceDocument.CreateProjectFileName(explicitFiles[0], TraceDocument.CreateProjectNameMode.DirectoryFromName, true, ref projectFile, ref projectName); 
                        fileRange = TraceFileRangeType.ExplicitFiles;
                    }
                    break;
            }
			if (this.DocumentIsNew)
			{
				this.DocumentNameTxt.Text = projectName;
				this.ProjectFileSel.SelectedPath = projectFile;
			}
            this.CurrentFileRange = fileRange;
            this.InputFilesSel.SelectedPath = filePath;
            this.ExplicitTraceFiles = explicitFiles;

            // Optimální chování:
            List<string> fileList = TraceDocument.CreateFileList(fileRange, filePath, explicitFiles);
            int fileCount = fileList.Count;
            this.PreLoadFilesChk.Checked = (fileCount < 15);
            this.WatchTraceChangesChk.Checked = (fileRange == TraceFileRangeType.OneDirectory);

            // Optimální filtr:
            string presetName = TraceDocument.GetOptimalPresetName(fileCount);
            int presetLevel = TraceDocument.GetPresetIndex(presetName, 2);
            string filter = TraceDocument.GetFilterForPreset(presetName);

            this.PresetDetailLevelProjectBar.Value = presetLevel;
            this.PresetDetailLevelFilterBar.Value = presetLevel;
            this._StoreFilterIntoCheckBoxes(filter);
        }
        //private void CreateProjectFileName(string inputPath, CreateProjectNameMode nameMode, bool uniqueName, ref string projectFile, ref string projectName)
        //{
        //    System.IO.FileInfo fi;
        //    System.IO.DirectoryInfo di;
        //    switch (nameMode)
        //    {
        //        case CreateProjectNameMode.FullNameCopy:
        //            fi = new System.IO.FileInfo(inputPath);
        //            projectFile = TraceDocument.CreateProjectFile(fi.Directory, fi.Name);
        //            projectName = TraceDocument.CreateProjectName(fi.Directory, fi.Name);
        //            break;
        //        case CreateProjectNameMode.DirectoryFromName:
        //            fi = new System.IO.FileInfo(inputPath);
        //            projectFile = TraceDocument.CreateProjectFile(fi.Directory, null);
        //            projectName = TraceDocument.CreateProjectName(fi.Directory, null);
        //            break;
        //        case CreateProjectNameMode.Directory:
        //            di = new System.IO.DirectoryInfo(inputPath);
        //            projectFile = TraceDocument.CreateProjectFile(di, null);
        //            projectName = TraceDocument.CreateProjectName(di, null);
        //            break;
        //    }
        //    if (!String.IsNullOrEmpty(projectFile))
        //        projectFile = TraceDocument.CreateProjectName(projectFile, uniqueName, ref projectName);
        //}
        //private string CreateProjectFile(System.IO.DirectoryInfo dirInfo, string fileName)
        //{
        //    return System.IO.Path.Combine(dirInfo.FullName, CreateProjectName(dirInfo, fileName) + "." + TraceDocument.PROJECT_EXTENSION);
        //}
        //private string CreateProjectName(System.IO.DirectoryInfo dirInfo, string fileName)
        //{
        //    string name = "";
        //    int cnt = 0;
        //    System.IO.DirectoryInfo di = dirInfo;
        //    while (cnt < 2 && di != null)
        //    {   // Jméno bude vypadat jako jména UP adresářů (v jedné řadě), složky oddělené "-", budou tam dvě složky s názvem delším (nebo rovným) než 3 znaky, kratší složky tam budou taky ale nepočítají se:
        //        // Takže z adresáře "C:\DavidPrac\TraceVisualiser\Kordarna\2012-10-18\B\" bude vytvořeno jméno "Kordarna-2012-10-18-B", 
        //        //  z adresáře "C:\DavidPrac\TraceVisualiser\Brano\2012-10-12b\" bude "Brano-2012-10-12b", atd.
        //        name = di.Name + (name.Length == 0 ? "" : "-") + name;
        //        if (di.Name.Length >= 3)
        //            cnt++;
        //        di = di.Parent;
        //    }
        //    return name;
        //}
        void SimplePanel_Run(object sender, EventArgs e)
        {
            this.OnRunDocument();
        }
        private void _ResizePageSimple()
        {
        }
        private TabPage TabPageSimple;
        private SimpleProjectPanelMed SimplePanel;
        #endregion
        #region TabPage: Doc
        private void _InitPageDoc()
		{
			this.TabPageDoc = new TabPage();
			this.TabPages.Add(this.TabPageDoc);
			this.TabPageDoc.Bounds = this.ClientRectangle;

			this.DocumentNameLbl = new Label();
			this.DocumentNameTxt = new TextBox();
			this.ProjectFileLbl = new Label();
			this.ProjectFileSel = new FileSelectPanel();
			this.TraceFileRangeLbl = new Label();
			this.TraceFileRangeCmb = new ComboBox();
			this.InputFilesLbl = new Label();
			this.InputFilesSel = new FileSelectPanel();
            this.PreLoadFilesChk = new CheckBox();
            this.WatchTraceChangesChk = new CheckBox();
            this.PresetDetailLevelLbl = new Label();
            this.PresetDetailLevelProjectBar = new TrackBar();
			//this.PresetTrackBar = new DTrackBar();
			this.FileListBox = new ListBox();
			this.FileRemoveBtn = new Button();

			int tabIndex = 0;

			// TabPageDoc
			this.TabPageDoc.Text = " Projekt ";
			this.TabPageDoc.UseVisualStyleBackColor = true;

			// DocumentGrp
			this.TabPageDoc.Controls.Add(this.FileRemoveBtn);
			this.TabPageDoc.Controls.Add(this.FileListBox);
			//this.TabPageDoc.Controls.Add(this.PresetTrackBar);
		    this.TabPageDoc.Controls.Add(this.PresetDetailLevelProjectBar);
            this.TabPageDoc.Controls.Add(this.PresetDetailLevelLbl);
            this.TabPageDoc.Controls.Add(this.WatchTraceChangesChk);
            this.TabPageDoc.Controls.Add(this.PreLoadFilesChk);
			this.TabPageDoc.Controls.Add(this.InputFilesSel);
			this.TabPageDoc.Controls.Add(this.InputFilesLbl);
			this.TabPageDoc.Controls.Add(this.ProjectFileSel);
			this.TabPageDoc.Controls.Add(this.ProjectFileLbl);
			this.TabPageDoc.Controls.Add(this.TraceFileRangeCmb);
			this.TabPageDoc.Controls.Add(this.TraceFileRangeLbl);
			this.TabPageDoc.Controls.Add(this.DocumentNameTxt);
			this.TabPageDoc.Controls.Add(this.DocumentNameLbl);

            int top = 12;
            Size size = this.ClientSize;

			// DocumentNameLbl
			this.DocumentNameLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.DocumentNameLbl.Location = new System.Drawing.Point(6, top + 3);
			this.DocumentNameLbl.Name = "DocumentNameLbl";
			this.DocumentNameLbl.Size = new System.Drawing.Size(140, 15);
			this.DocumentNameLbl.TabIndex = 0;
			this.DocumentNameLbl.Text = "Název projektu:";
			this.DocumentNameLbl.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

			// DocumentNameTxt
			this.DocumentNameTxt.Anchor = (AnchorStyles)(AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right);
			this.DocumentNameTxt.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.DocumentNameTxt.Location = new System.Drawing.Point(147, top);
			this.DocumentNameTxt.Name = "DocumentNameTxt";
			this.DocumentNameTxt.Size = new System.Drawing.Size(315, 21);
			this.DocumentNameTxt.TabIndex = tabIndex++;
            top += 23;

			// DocumentFileLbl
			this.ProjectFileLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.ProjectFileLbl.Location = new System.Drawing.Point(6, top + 3);
			this.ProjectFileLbl.Name = "DocumentFileLbl";
			this.ProjectFileLbl.Size = new System.Drawing.Size(140, 15);
			this.ProjectFileLbl.TabIndex = tabIndex++;
			this.ProjectFileLbl.Text = "Soubor s projektem:";
			this.ProjectFileLbl.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

			// ProjectFileSel
			this.ProjectFileSel.Anchor = (AnchorStyles)(AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right);
			this.ProjectFileSel.Location = new System.Drawing.Point(147, top);
			this.ProjectFileSel.Name = "ProjectFileSel";
			this.ProjectFileSel.Size = new System.Drawing.Size(315, 23);
			this.ProjectFileSel.DefaultPath = Steward.AppConfig.LastProjectPath;
			this.ProjectFileSel.SelectMode = PathSelectMode.PutFile;
            this.ProjectFileSel.Filter = "VisualTrace project (*." + TraceDocument.PROJECT_EXTENSION + ")|*." + TraceDocument.PROJECT_EXTENSION + "|All files (*.*)|*.*";
			this.ProjectFileSel.Title = "Select file for project";
			this.ProjectFileSel.TabIndex = tabIndex++;
            top += 23;

			// TraceFileRangeLbl
			this.TraceFileRangeLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.TraceFileRangeLbl.Location = new System.Drawing.Point(6, top + 3);
			this.TraceFileRangeLbl.Name = "TraceFileRangeLbl";
			this.TraceFileRangeLbl.Size = new System.Drawing.Size(140, 15);
			this.TraceFileRangeLbl.TabIndex = tabIndex++;
			this.TraceFileRangeLbl.Text = "Rozsah souborů:";
			this.TraceFileRangeLbl.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

			// TraceFileRangeCmb
			this.TraceFileRangeCmb.Anchor = (AnchorStyles)(AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right);
			this.TraceFileRangeCmb.DropDownStyle = ComboBoxStyle.DropDownList;
			this.TraceFileRangeCmb.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.TraceFileRangeCmb.FormattingEnabled = true;
			this.TraceFileRangeCmb.Items.AddRange(new object[] {
                "Jeden vybraný soubor",
                "Všechny soubory v jednom adresáři",
                "Všechny soubory i soubory v podadresářích",
                "Jednotlivě vybrané soubory (Drag & Drop)"});
			this.TraceFileRangeCmb.Location = new System.Drawing.Point(147, top);
			this.TraceFileRangeCmb.Name = "TraceFileRangeCmb";
			this.TraceFileRangeCmb.Size = new System.Drawing.Size(315, 23);
			this.TraceFileRangeCmb.TabIndex = tabIndex++;
			this.TraceFileRangeCmb.SelectedIndexChanged += new EventHandler(TraceFileRangeCmb_SelectedIndexChanged);
            top += 25;

			// InputFilesLbl
			this.InputFilesLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.InputFilesLbl.Location = new System.Drawing.Point(6, top + 3);
			this.InputFilesLbl.Name = "InputFilesLbl";
			this.InputFilesLbl.Size = new System.Drawing.Size(140, 15);
			this.InputFilesLbl.TabIndex = tabIndex++;
			this.InputFilesLbl.Text = "Vstupní soubor(y):";
			this.InputFilesLbl.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

			// InputFilesSel
			this.InputFilesSel.Anchor = (AnchorStyles)(AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right);
			this.InputFilesSel.Location = new System.Drawing.Point(147, top);
			this.InputFilesSel.Name = "InputFilesSel";
			this.InputFilesSel.Size = new System.Drawing.Size(315, 23);
			this.InputFilesSel.DefaultPath = Steward.AppConfig.LastTracePath;
			this.InputFilesSel.SelectMode = PathSelectMode.GetFile;
            this.InputFilesSel.Filter = TraceDocument.GetOpenTraceFilter("All files (*.*)|*.*");
			this.InputFilesSel.TabIndex = tabIndex++;
            this.InputFilesSel.SelectedPathChanged += new EventHandler(InputFilesSel_SelectedPathChanged);
            top += 25;

            // PreLoadFilesChk
            this.PreLoadFilesChk.Location = new System.Drawing.Point(147, top);
            this.PreLoadFilesChk.Name = "PreLoadFilesChk";
            this.PreLoadFilesChk.Text = "Přednačítat obsah trace souborů";
            this.PreLoadFilesChk.AutoSize = true;
            this.PreLoadFilesChk.TabIndex = tabIndex++;
            top += 21;

            // WatchTraceChangesChk
            this.WatchTraceChangesChk.Location = new System.Drawing.Point(147, top);
            this.WatchTraceChangesChk.Name = "WatchTraceChangesChk";
            this.WatchTraceChangesChk.Text = "Hlídat změny trace souborů";
            this.WatchTraceChangesChk.AutoSize = true;
            this.WatchTraceChangesChk.TabIndex = tabIndex++;
            this.WatchTraceChangesChk.CheckedChanged += new EventHandler(WatchTraceChangesChk_CheckedChanged);
            top += 19;

            // PresetDetailLevelLbl
            this.PresetDetailLevelLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
            this.PresetDetailLevelLbl.Location = new System.Drawing.Point(6, top + 3);
            this.PresetDetailLevelLbl.Name = "PresetDetailLevelLbl";
            this.PresetDetailLevelLbl.Size = new System.Drawing.Size(140, 15);
            this.PresetDetailLevelLbl.TabIndex = tabIndex++;
            this.PresetDetailLevelLbl.Text = "Úroveň detailů:";
            this.PresetDetailLevelLbl.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

            // PresetDetailLevelBar
            this._PrepareTrackBarLevel(this.PresetDetailLevelProjectBar, "PresetDetailLevelProjectBar", new Point(147, top), Orientation.Horizontal, ref tabIndex);
            top += this.PresetDetailLevelProjectBar.Height + 4;

			//this.PresetTrackBar.Location = new Point(this.PresetDetailLevelProjectBar.Right + 6, this.PresetDetailLevelProjectBar.Top);
			//this.PresetTrackBar.Size = this.PresetDetailLevelProjectBar.Size;
            
			// FileListBox
			this.FileListBox.Anchor = Anchor = (AnchorStyles)(AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom);
			this.FileListBox.FormattingEnabled = true;
			this.FileListBox.Location = new System.Drawing.Point(147, top);
			this.FileListBox.Name = "FileListBox";
			this.FileListBox.Size = new System.Drawing.Size(315, size.Height - top - 3);
			this.FileListBox.Visible = false;
			this.FileListBox.TabIndex = tabIndex++;

			// FileRemoveBtn
			this.FileRemoveBtn.Anchor = ((AnchorStyles)((AnchorStyles.Top | AnchorStyles.Left)));
			this.FileRemoveBtn.Location = new System.Drawing.Point(70, top);
			this.FileRemoveBtn.Name = "FileRemoveBtn";
			this.FileRemoveBtn.Size = new System.Drawing.Size(75, 23);
			this.FileRemoveBtn.Visible = false;
			this.FileRemoveBtn.TabIndex = tabIndex++;
			this.FileRemoveBtn.Text = "Odebrat";
			this.FileRemoveBtn.UseVisualStyleBackColor = true;
		}
		// _PageDoc:
		private TabPage TabPageDoc;
		private TextBox DocumentNameTxt;
		private Label DocumentNameLbl;
		private ComboBox TraceFileRangeCmb;
		private Label TraceFileRangeLbl;
		private Label ProjectFileLbl;
		private FileSelectPanel ProjectFileSel;
		private FileSelectPanel InputFilesSel;
        private CheckBox PreLoadFilesChk;
        private CheckBox WatchTraceChangesChk;
        private Label PresetDetailLevelLbl;
        private TrackBar PresetDetailLevelProjectBar;
		//private DTrackBar PresetTrackBar;
		private Label InputFilesLbl;
		private Button FileRemoveBtn;
		private ListBox FileListBox;
        /// <summary>
        /// Po změně rozsahu souborů
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TraceFileRangeCmb_SelectedIndexChanged(object sender, EventArgs e)
        {
            this._TraceFileRangeShowFiles();
            this._TraceDocumentPresetOptimalFilters();
            this._TraceFileRangeApplySelectMode();
            this._TraceWatchNewFilesCheck();
        }
        /// <summary>
        /// Po změně vybrané cesty k souborům
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InputFilesSel_SelectedPathChanged(object sender, EventArgs e)
        {
            this._TraceDocumentPresetOptimalFilters();
        }
        /// <summary>
        /// Po změně zaškrtnutí zaškrtávátka WatchTraceChangesChk ("Hlídat změny trace souborů")
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void WatchTraceChangesChk_CheckedChanged(object sender, EventArgs e)
        {
            this._TraceWatchNewFilesCheck();
        }
        /// <summary>
        /// Urči optimální filtry a nastaví je do vizuální vrstvy.
        /// Nepracuje s instancí linkovaného dokumentu (změny se nemusí promítnout do dat)!
        /// </summary>
        private void _TraceDocumentPresetOptimalFilters()
        {
            if (this._SuppressDetailLevel) return;             // true je v době plnění controlu daty z dokumentu

            string presetName = TraceDocument.GetOptimalPresetName(this.CurrentFileRange, this.InputFilesSel.SelectedPath, null);
            int presetLevel = TraceDocument.GetPresetIndex(presetName, 2);
            string filter = TraceDocument.GetFilterForPreset(presetName);

            this.PresetDetailLevelProjectBar.Value = presetLevel;
            this.PresetDetailLevelFilterBar.Value = presetLevel;
            this._StoreFilterIntoCheckBoxes(filter);
        }
        private void _TraceFileRangeShowFiles()
        {
            bool fileVisible = (this.CurrentFileRange == TraceFileRangeType.ExplicitFiles);
            if (this.FileListBox.Visible != fileVisible)
            {
                this.FileListBox.Visible = fileVisible;
                this.FileRemoveBtn.Visible = fileVisible;
            }
        }
        private void _TraceFileRangeApplySelectMode()
        {
            PathSelectMode mode = PathSelectMode.GetFile;
            switch (this.CurrentFileRange)
            {
                case TraceFileRangeType.OneFile:
                    mode = PathSelectMode.GetFile;
                    break;
                case TraceFileRangeType.OneDirectory:
                    mode = PathSelectMode.GetFile;
                    break;
                case TraceFileRangeType.AllSubdirectories:
                    mode = PathSelectMode.GetDirectory;
                    break;
            }
            this.InputFilesSel.SelectMode = mode;
        }
        /// <summary>
        /// Prověří, zda je kompatibilní předvolba režimu souborů () a zaškrtávátka WatchTraceChangesChk ("Hlídat změny trace souborů")
        /// </summary>
        /// <param name="silent"></param>
        private void _TraceWatchNewFilesCheck()
        {
            bool watchTraceChangesEnabled = true;
            TraceFileRangeType fileRange = this.CurrentFileRange;
            if (fileRange != TraceFileRangeType.OneDirectory)
            {
                watchTraceChangesEnabled = false;
                if (this.WatchTraceChangesChk.Checked)
                    this.WatchTraceChangesChk.Checked = false;          // bacha, tady se provede event WatchTraceChangesChk_CheckedChanged() a znovu se dostaneme do zdejší metody, ale už ne do tohoto příkazu!
            }
            if (this.WatchTraceChangesChk.Enabled != watchTraceChangesEnabled)
                this.WatchTraceChangesChk.Enabled = watchTraceChangesEnabled;
        }
		#endregion
		#region TabPage: Filter
		private void _InitPageFilter()
		{
			this.TabPageFilter = new TabPage();
			this.TabPages.Add(this.TabPageFilter);
			this.TabPageFilter.Bounds = this.ClientRectangle;

            int tabIndex = 0;

			// Layout:
			int x0 = 8;
			Size buttonSize = new System.Drawing.Size(106, 24);
			int x1 = 100;
			int x2 = 220;
			int x3 = 310;
			int x4 = 400;
			int yc = 8;
			int hc = 18;

			int yb = 12;
			int hb = buttonSize.Height + 2;

			this.PresetLabel = new Label() { Text = "Úroveň detailů:", Location = new Point(x0, yb), AutoSize = true };
            this.PresetDetailLevelFilterBar = new TrackBar();
            this._PrepareTrackBarLevel(this.PresetDetailLevelFilterBar, "PresetDetailLevelFilterBar", new Point(x0, yb + 25), Orientation.Vertical, ref tabIndex);

            this.CheckFilterAll = new CheckBox() { Text = "Vše", Tag = TraceDocument.FILTER_ALL, AutoSize = true, Location = new Point(x1, yc) };
            
            this.CheckFilterSql = new CheckBox() { Text = "SQL příkazy", Tag = TraceDocument.FILTER_SQL, AutoSize = true, Location = new Point(x1, (yc += hc)) };
            this.CheckFilterCowley = new CheckBox() { Text = "Cowley", Tag = TraceDocument.FILTER_COWLEY, AutoSize = true, Location = new Point(x1, (yc += hc)) };
			this.CheckFilterInstance = new CheckBox() { Text = "Instance.All", Tag = TraceDocument.FILTER_INSTANCE_ALL, AutoSize = true, Location = new Point(x1, (yc += hc)) };
			this.CheckFilterInstCore = new CheckBox() { Text = "Retr.,Upd.", Tag = TraceDocument.FILTER_INSTANCE_RUR, AutoSize = true, Location = new Point(x2, yc) };
			this.CheckFilterInstChange = new CheckBox() { Text = "Change", Tag = TraceDocument.FILTER_INSTANCE_CHANGE, AutoSize = true, Location = new Point(x3, yc) };
			this.CheckFilterInstIom = new CheckBox() { Text = "IOM", Tag = TraceDocument.FILTER_INSTANCE_IOM, AutoSize = true, Location = new Point(x4, yc) };

            this.CheckFilterCoreThread = new CheckBox() { Text = "Thread", Tag = TraceDocument.FILTER_THREAD, AutoSize = true, Location = new Point(x1, (yc += hc)) };
			this.CheckFilterCoreFormat = new CheckBox() { Text = "Format", Tag = TraceDocument.FILTER_FORMAT, AutoSize = true, Location = new Point(x1, (yc += hc)) };
			this.CheckFilterCoreForms = new CheckBox() { Text = "Forms.All", Tag = TraceDocument.FILTER_FORMS, AutoSize = true, Location = new Point(x1, (yc += hc)) };
            this.CheckFilterCoreFormsOpen = new CheckBox() { Text = "Form.Open", Tag = TraceDocument.FILTER_FORMS_OPEN, AutoSize = true, Location = new Point(x2, yc) };

            this.CheckFilterCoreCache = new CheckBox() { Text = "Cache", Tag = TraceDocument.FILTER_CACHE, AutoSize = true, Location = new Point(x1, (yc += hc)) };

			this.CheckFilterCoreSysMsg = new CheckBox() { Text = "SysMessage.All", Tag = TraceDocument.FILTER_SYSMSG_ALL, AutoSize = true, Location = new Point(x1, (yc += hc)) };
			this.CheckFilterCoreSysMsgError = new CheckBox() { Text = "Error", Tag = TraceDocument.FILTER_SYSMSG_ERROR, AutoSize = true, Location = new Point(x2, yc) };
			this.CheckFilterCoreSysMsgWarning = new CheckBox() { Text = "Warning", Tag = TraceDocument.FILTER_SYSMSG_WARNING, AutoSize = true, Location = new Point(x3, yc) };
			this.CheckFilterCoreSysMsgInfo = new CheckBox() { Text = "Info", Tag = TraceDocument.FILTER_SYSMSG_INFO, AutoSize = true, Location = new Point(x4, yc) };

			this.TabPageFilter.Controls.Add(this.PresetLabel);
            this.TabPageFilter.Controls.Add(this.PresetDetailLevelFilterBar);
            
            this.TabPageFilter.Controls.Add(this.CheckFilterAll);
			this.TabPageFilter.Controls.Add(this.CheckFilterSql);
			this.TabPageFilter.Controls.Add(this.CheckFilterCowley);
			this.TabPageFilter.Controls.Add(this.CheckFilterInstance);
			this.TabPageFilter.Controls.Add(this.CheckFilterInstCore);
			this.TabPageFilter.Controls.Add(this.CheckFilterInstChange);
			this.TabPageFilter.Controls.Add(this.CheckFilterInstIom);

			this.TabPageFilter.Controls.Add(this.CheckFilterCoreThread);
			this.TabPageFilter.Controls.Add(this.CheckFilterCoreFormat);
			this.TabPageFilter.Controls.Add(this.CheckFilterCoreForms);
            this.TabPageFilter.Controls.Add(this.CheckFilterCoreFormsOpen);
            this.TabPageFilter.Controls.Add(this.CheckFilterCoreCache);
			this.TabPageFilter.Controls.Add(this.CheckFilterCoreSysMsg);
			this.TabPageFilter.Controls.Add(this.CheckFilterCoreSysMsgError);
			this.TabPageFilter.Controls.Add(this.CheckFilterCoreSysMsgWarning);
			this.TabPageFilter.Controls.Add(this.CheckFilterCoreSysMsgInfo);

			// TabPageDoc
			this.TabPageFilter.Text = " Vlastnosti ";
			this.TabPageFilter.UseVisualStyleBackColor = true;
		}
		private void _PreparePresetButton(Button presetButton, EventHandler onClick)
		{
			presetButton.FlatStyle = FlatStyle.System; // FlatStyle.Flat;
			presetButton.FlatAppearance.BorderSize = 0;
			// presetButton.BackColor = Color.LightGray;
			presetButton.FlatAppearance.MouseOverBackColor = Color.LightYellow;
			presetButton.FlatAppearance.MouseDownBackColor = Color.LightSkyBlue;
			presetButton.Click += onClick;
		}
		private TabPage TabPageFilter;
		private Label PresetLabel;
        private TrackBar PresetDetailLevelFilterBar;
        private CheckBox CheckFilterAll;
		private CheckBox CheckFilterSql;
		private CheckBox CheckFilterCowley;
		private CheckBox CheckFilterInstance;
		private CheckBox CheckFilterInstCore;
		private CheckBox CheckFilterInstChange;
		private CheckBox CheckFilterInstIom;
		private CheckBox CheckFilterCoreThread;
		private CheckBox CheckFilterCoreFormat;
		private CheckBox CheckFilterCoreForms;
        private CheckBox CheckFilterCoreFormsOpen;
        private CheckBox CheckFilterCoreCache;
		private CheckBox CheckFilterCoreSysMsg;
		private CheckBox CheckFilterCoreSysMsgError;
		private CheckBox CheckFilterCoreSysMsgWarning;
		private CheckBox CheckFilterCoreSysMsgInfo;
		#endregion
		#region Preset button / trackbar
        /// <summary>
        /// Do předaného TrackBaru pro presety filtrů nastaví potřebné vlastnosti.
        /// </summary>
        /// <param name="bar"></param>
        /// <param name="location"></param>
        /// <param name="orientation"></param>
        private void _PrepareTrackBarLevel(TrackBar bar, string name, Point location, Orientation orientation, ref int tabIndex)
        {
            bar.Location = location;
            bar.Name = name;
            bar.Minimum = 0;
            bar.Maximum = this._FilterPresets.Length - 1;
            bar.SmallChange = 1;
            bar.LargeChange = 1;
            bar.TickFrequency = 1;
            bar.TickStyle = TickStyle.None;
            bar.Orientation = orientation;
            switch (orientation)
            {
                case Orientation.Horizontal:
                    bar.Size = new Size(110, 15);
                    break;
                case Orientation.Vertical:
                    bar.Size = new Size(15, 110);
                    break;
            }
            bar.TabIndex = tabIndex++;
            bar.ValueChanged += new EventHandler(_PresetDetailLevel_ValueChanged);
        }
        void _PresetDetailLevel_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                this._SuppressDetailLevel = true;

                TrackBar bar = sender as TrackBar;
                if (bar != null)
                {
                    int value = bar.Value;

                    if (!Object.ReferenceEquals(sender, this.PresetDetailLevelProjectBar))
                        this.PresetDetailLevelProjectBar.Value = value;
                    if (!Object.ReferenceEquals(sender, this.PresetDetailLevelFilterBar))
                        this.PresetDetailLevelFilterBar.Value = value;

                    string preset = (value >= 0 && value < this._FilterPresets.Length ? this._FilterPresets[value] : null);
                    this._StoreFilterIntoCheckBoxes(TraceDocument.GetFilterForPreset(preset));
                }
            }
            finally
            {
                this._SuppressDetailLevel = false;
            }
        }
        private bool _SuppressDetailLevel;
		/// <summary>
		/// Na základě textu filtru nastaví do odpovídajících checkboxů stav Checked
		/// </summary>
		/// <param name="buttonTag"></param>
		/// <returns></returns>
		private void _StoreFilterIntoCheckBoxes(string filters)
		{
            string[] fi = filters.Split(';');
            List<string> filterList = new List<string>();
            foreach (string f in fi)
                filterList.Add(f.Trim());

            foreach (Control control in this.TabPageFilter.Controls)
            {
                CheckBox checkBox = control as CheckBox;
                if (checkBox != null)
                {
                    string filter = checkBox.Tag as string;
                    if (!String.IsNullOrEmpty(filter))
                    {
                        checkBox.Checked = (filterList.Contains(filter));
                    }
                }
            }
		}
        /// <summary>
        /// Z checkboxů sestaví a vrátí filtrační výraz
        /// </summary>
        /// <returns></returns>
        private string _ReadFilterFromCheckBoxes()
        {
            string result = "";
            foreach (Control control in this.TabPageFilter.Controls)
            {
                CheckBox checkBox = control as CheckBox;
                if (checkBox != null)
                {
                    string filter = checkBox.Tag as string;
                    if (!String.IsNullOrEmpty(filter) && checkBox.Checked)
                        result += (result.Length == 0 ? "" : ";") + filter;
                }
            }
            return result;
        }
        /// <summary>
        /// Sada názvů presetů pro filtry (přednastavené sady pro filtrování trace souborů)
        /// </summary>
        private string[] _FilterPresets;
		#endregion
		#region Document get; set (collect)
		/// <summary>
        /// Data TraceDocument
        /// </summary>
		[Browsable(false)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public TraceDocument Document
		{
			get { this._DocumentGet(); return _Document; }
			set { this._Document = value; this._DocumentSet(); }
		}
		/// <summary>
		/// Dokument je nový, dosud neuložený = je možno v něm měnit jméno souboru a projektu
		/// </summary>
		[Browsable(false)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public bool DocumentIsNew
		{
			get { return _DocumentIsNew; }
			set { _DocumentIsNew = value; this._SetProjectEnabled(); }
		}
		private bool _DocumentIsNew;
		private void _SetProjectEnabled()
		{
			bool projEnabled = this.DocumentIsNew;
			this.DocumentNameTxt.Enabled = projEnabled;
			this.ProjectFileSel.Enabled = projEnabled;
		}
		/// <summary>
		/// Potvrzení hodnoty při dokončení editace.
		/// Objekt this (Panel) sám o sobě nemá tlačítko OK, a interaktivní editace neukládá data do datového objektu this.Document.
		/// Pokud tedy parent svými tlačítky / toolbarem zaregistruje požadavek na uložení, tak vepíše sem hodnotu true (DocumentOk = true),
		/// čímž dojde k propsání vizuálních hodnot do objektu this.Document.
		/// Pak je možno dokument z objektu this převzít, anebo - pokud je referencován odjinud už od dřívějška, pak obsahuje aktuální editovaná data.
        /// Současně dojde k tomu, že cesty zadané do projektu se vepíšou do konfigurace jako LastUsed.
        /// Dále se vyvolá event 
		/// </summary>
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public bool DocumentOk
		{
			get { return true; }
			set
			{
                if (value)
                {
                    this._PathSave();
                    this._DocumentGet();
                }
			}
		}
        /// <summary>
        /// Uloží si cesty zadané v projektu do paměti v konfiguraci
        /// </summary>
        private void _PathSave()
        {
            string projectFile = this.ProjectFileSel.SelectedPath;
            if (!String.IsNullOrEmpty(projectFile))
                Steward.AppConfig.LastProjectPath = System.IO.Path.GetDirectoryName(projectFile);

            string tracePath = this.InputFilesSel.SelectedPath;
            if (!String.IsNullOrEmpty(tracePath))
            {
                if (this.CurrentFileRange == TraceFileRangeType.AllSubdirectories)
                    Steward.AppConfig.LastTracePath = tracePath;
                else
                    Steward.AppConfig.LastTracePath = System.IO.Path.GetDirectoryName(tracePath);
            }
        }
		private TraceDocument _Document;
        /// <summary>
        /// Do vizuální vrstvy vepíše data dokumentu
        /// </summary>
		private void _DocumentSet()
		{
			TraceDocument document = this._Document;

            this._SuppressDetailLevel = true;

            this.DocumentNameTxt.Text = document.DocumentName;
            this.CurrentFileRange = document.TraceFileRange;
            this.ProjectFileSel.SelectedPath = document.ProjectFile;
            this.InputFilesSel.SelectedPath = document.TracePath;
            this.ExplicitTraceFiles = document.ExplicitTraceFiles;
            this.PreLoadFilesChk.Checked = document.PreLoadFiles;
            this.WatchTraceChangesChk.Checked = document.WatchTraceChanges;

            this.PresetDetailLevelProjectBar.Value = document.PresetDetailLevel;
            this.PresetDetailLevelFilterBar.Value = document.PresetDetailLevel;
            this._StoreFilterIntoCheckBoxes(document.Filter);

			this.DocumentIsNew = !document.ProjectFileSaved;
			bool simpleVisible = Steward.AppConfig.DocSimpleEnabled;
			if (!simpleVisible)
			{
				this.TabPageSimple.Hide();
				this.TabPages.Remove(this.TabPageSimple);
			}
			if (!this.DocumentIsNew && simpleVisible)
				this.SimplePanel.DocumentSet(GetFileSelect(document), document.TracePath, document.ExplicitTraceFiles);

			// Aktivovat stranu 2 (index [1]) jen pro případ, kdy je vidět i simple panel, a dokument není nový:
			if (simpleVisible && !this.DocumentIsNew)
				this.SelectTab(1);
			else
				this.SelectTab(0);

            this._SuppressDetailLevel = false;
        }
		protected SimpleProjectPanelAbs.FileSelectType GetFileSelect(TraceDocument document)
		{
			if (document.TraceFileRange == TraceFileRangeType.OneFile)
				return SimpleProjectPanelAbs.FileSelectType.OneFile;
			if (document.TraceFileRange == TraceFileRangeType.OneDirectory)
				return SimpleProjectPanelAbs.FileSelectType.OneDirectory;
			if (document.TraceFileRange == TraceFileRangeType.AllSubdirectories)
				return SimpleProjectPanelAbs.FileSelectType.SubDirectory;
			if (document.TraceFileRange == TraceFileRangeType.ExplicitFiles)
				return SimpleProjectPanelAbs.FileSelectType.ExplicitFiles;
			return SimpleProjectPanelAbs.FileSelectType.None;
		}
		/// <summary>
        /// Do dokumentu vepíše data z vizuální vrstvy
        /// </summary>
		private void _DocumentGet()
		{
            if (this._Document == null)
                this._Document = new TraceDocument();
            TraceDocument document = this._Document;

			if (this.DocumentIsNew)
			{
				document.DocumentName = this.DocumentNameTxt.Text;
				document.ProjectFile = this.ProjectFileSel.SelectedPath;
			}
            document.TraceFileRange = this.CurrentFileRange;
            document.TracePath = this.InputFilesSel.SelectedPath;
            document.ExplicitTraceFiles = this.ExplicitTraceFiles;
            document.PreLoadFiles = this.PreLoadFilesChk.Checked;
            document.WatchTraceChanges = this.WatchTraceChangesChk.Checked;
            document.PresetDetailLevel = this.PresetDetailLevelProjectBar.Value;
            document.Filter = this._ReadFilterFromCheckBoxes();
		}
        /// <summary>
        /// Seznam explicitních souborů
        /// </summary>
        protected List<string> ExplicitTraceFiles;
        /// <summary>
        /// Hodnota TraceFileRangeType odpovídající aktuální volbě v combo boxu this.TraceFileRangeCmb
        /// </summary>
        protected TraceFileRangeType CurrentFileRange
        {
            get
            {
                int index = this.TraceFileRangeCmb.SelectedIndex;
                if (index >= 0 && index < 4)
                    return (TraceFileRangeType)(index + 1);
                else
                    return TraceFileRangeType.None;
            }
            set
            {
                int range = ((int)value) - 1;         // Hodnota 1 = OneFile se zobrazuje v položce s indexem 0, používají se hodnoty 0 - 3
                if (range >= 0 && range < 4)
                    this.TraceFileRangeCmb.SelectedIndex = range;
                else
                    this.TraceFileRangeCmb.SelectedIndex = 0;

            }
        }
		#endregion
	}
}
